<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery1.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我的询价</el-menu-item>
      <el-menu-item index="all">全部询价</el-menu-item>
    </el-menu>

    <div style="margin-top:40px">
        <el-form :inline="true" :model="listQuery1" size="mini" label-width="100px">
          <el-form-item label="询价日期：">
            <el-date-picker
              v-model="listQuery1.inquiryDate"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="规格型号：">
            <el-select v-model="listQuery1.kingGoodsId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in goodsList"
                :key="item.kingId"
                :label="item.goodsSn"
                :value="item.kingId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="业务员：">
            <el-select v-model="listQuery1.userId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in userOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              @click="handleSearchList1()"
              type="primary">
              查询
            </el-button>
            <el-button
              @click="showAddForm()"
              type="primary">
              新增
            </el-button>
            <el-button
              v-if="inquiryExport"
              @click="downloadExcel()"
              type="primary">
              导出
            </el-button>
          </el-form-item>
        </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
          <el-radio-group v-model="listQuery1.inquiryState" size="small" @change="changeInquiryState">
            <el-radio-button label="0">待报价</el-radio-button>
            <el-radio-button label="20">已报价</el-radio-button>
            <el-radio-button label="">全部</el-radio-button>
          </el-radio-group>
          <el-table
            v-loading="listLoading1"
            :data="tableData1"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column
              label="询价日期"
              width="150"
              align="center">
              <template slot-scope="scope">
                {{scope.row.inquiryTime}}
              </template>
            </el-table-column>
            <el-table-column  label="询价类型" width="100" prop="orderSn" align="center">
              <template slot-scope="scope">
                {{scope.row.inquiryType}}
              </template>
            </el-table-column>
            <el-table-column
              label="联系信息"
              width="150"
              align="center">
              <template slot-scope="scope">
                {{scope.row.contactName}}/{{scope.row.contactMobile}}
              </template>
            </el-table-column>
            <el-table-column
              label="客户行业"
              width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.customerIndustry}}
              </template>
            </el-table-column>
            <el-table-column
              label="采购评级"
              width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.customerLabel}}
              </template>
            </el-table-column>
            <el-table-column
              label="客户名称"
              width="150"
              header-align="center">
              <template slot-scope="scope">
                {{scope.row.customerName}}
              </template>
            </el-table-column>
            <el-table-column
              label="商品名称"
              width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.goodsName}}
              </template>
            </el-table-column>
            <el-table-column
              label="规格型号"
              width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.goodsSn}}
              </template>
            </el-table-column>
            <el-table-column
              label="数量"
              align="center"
              width="100">
              <template slot-scope="scope">
                {{scope.row.inquiryNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="期望交期"
              width="100">
              <template slot-scope="scope">
                {{scope.row.expectDeliverDays}}
              </template>
            </el-table-column>
            <el-table-column
              label="送货地址"
              header-align="center"
              width="150">
              <template slot-scope="scope">
                {{scope.row.receiveArea}}
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              header-align="center"
              width="200">
              <template slot-scope="scope">
                {{scope.row.inquiryRemark}}
              </template>
            </el-table-column>

            <el-table-column
              label="采购回复时间"
              width="150"
              align="center">
              <template slot-scope="scope">
                {{scope.row.offerTime}}
              </template>
            </el-table-column>
            <el-table-column
              label="回复时长"
              width="100"
              align="center">
              <template slot-scope="scope">
                  {{scope.row.diffMinutes}}
              </template>
            </el-table-column>
            <el-table-column
              label="采购报价"
              width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.offerPrice}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="交期"
              width="100">
              <template slot-scope="scope">
                {{scope.row.offerDeliverDays}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="采购员"
              width="100">
              <template slot-scope="scope">
                {{scope.row.offerUserName}}
              </template>
            </el-table-column>

            <el-table-column
              label="未成交原因"
              header-align="center"
              width="150">
              <template slot-scope="scope">
                {{scope.row.unOrderReason}}
              </template>
            </el-table-column>
            <el-table-column
              label="状态"
              width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.inquiryState | fifInquiryState}}
              </template>
            </el-table-column>

            <el-table-column
              width="100"
              fixed="right"
              label="操作"
              align="center">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.inquiryState == 0"
                  type="text"
                  size="mini"
                  @click="showCancelForm(scope.row,'cancel')">取消
                </el-button>
                <el-button
                  v-if="scope.row.inquiryState == 30"
                  type="text"
                  size="mini"
                  @click="showCancelForm(scope.row,'unOrder')">未成交原因
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery1.pageNum"
            :page-size="listQuery1.pageSize"
            :page-sizes="[10,15,20]"
            :total="count1">
          </el-pagination>
        </div>


    <!--新增询价-->
    <el-dialog
            :close-on-click-modal="false"
            title="新增询价"
            :visible.sync="dialogVisible"
            width="1000px">
      <el-form :model="addForm" size="small" label-width="100px" ref="addForm" :rules="rules">
        <el-form-item label="客户名称：" prop="customerName">
          <el-autocomplete
            clearable
            class="inline-input"
            value-key="customerName"
            :fetch-suggestions="querySearch"
            v-model="addForm.customerName"
            placeholder="请输入内容"
            @select="handleSelectCustomerName"
            :trigger-on-focus="false"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="采购评级：" prop="customerLabel">
          <el-select v-model="addForm.customerLabel"  placeholder="请选择" clearable>
            <el-option value="A类" label="A类" key="A类"></el-option>
            <el-option value="B类" label="B类" key="B类"></el-option>
            <el-option value="C类" label="C类" key="C类"></el-option>
            <el-option value="D类" label="D类" key="D类"></el-option>
            <el-option value="E类" label="E类" key="E类"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户行业：" prop="customerIndustry">
          <el-select v-model="addForm.customerIndustry" placeholder="请选择"  clearable>
            <el-option :value="item.cddValue" :label="item.cddValue" :key="item.cddValue" v-for="item in customerIndustryList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="询价商品：" >
            <div><el-button type="text" @click="addGoods">新增询价商品</el-button></div>
            <el-table :data="addForm.goodsList" border>
              <el-table-column
                min-width="200"
                label="询价商品"
                align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="`goodsList.${scope.$index}.kingGoodsId`" :rules="rules.kingGoodsId" label-width="0px">
                    <el-select
                      @change="changeGoods(scope.$index,scope.row.kingGoodsId)"
                      size="small"
                      v-model="scope.row.kingGoodsId"
                      filterable
                      remote
                      placeholder="请输入关键词"
                      :remote-method="((val)=>{remoteMethod(val, scope.$index)})"
                      :loading="goodsLoading">
                      <el-option
                        v-for="item in scope.row.list"
                        :key="item.kingGoodsId"
                        :label="item | fifitem"
                        :value="item.kingGoodsId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="询价数量"
                min-width="100"
                align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="`goodsList.${scope.$index}.inquiryNum`" :rules="rules.inquiryNum" label-width="0px">
                    <el-input v-model="scope.row.inquiryNum"  size="small"  style="width:65%"></el-input><span style="padding-left:10px;">吨</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="期望交期"
                min-width="100"
                align="center">
                    <template slot-scope="scope">
                      <el-form-item :prop="`goodsList.${scope.$index}.expectDeliverDays`" :rules="rules.expectDeliverDays" label-width="0px">
                        <el-input v-model="scope.row.expectDeliverDays"  size="small"  style="width:65%"></el-input><span style="padding-left:10px;">天</span>
                      </el-form-item>
                    </template>
              </el-table-column>

              <el-table-column
                label="送货地"
                min-width="150"
                align="center">
                <template slot-scope="scope">
                    <el-form-item :prop="`goodsList.${scope.$index}.receiveAreaList`" :rules="rules.receiveAreaList" label-width="0px">
                      <el-cascader
                        @change="changeArea(scope.$index,scope.row.receiveAreaList)"
                        v-model="scope.row.receiveAreaList"
                        :props="{ value: 'areaName',label:'areaName',children:'areaChildList' }"
                        :options="options"></el-cascader>
                    </el-form-item>
               </template>
              </el-table-column>
              <el-table-column
                label="操作"
                min-width="80"
                align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="delGoods(scope.$index)" :disabled="scope.$index==0">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
        </el-form-item>

        <el-form-item label="备注：">
            <el-input type="textarea" :rows="2" v-model="addForm.inquiryRemark"></el-input>
        </el-form-item>

        <el-form-item label="询价人：">
          {{name}}
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">发 布</el-button>
      </span>
    </el-dialog>

    <!--未成交原因-->
    <el-dialog
      :close-on-click-modal="false"
      title="未成交原因"
      :visible.sync="dialogVisible2"
      width="420px">
      <el-form :model="cancelForm" size="mini" label-width="120px" ref="cancelForm" :rules="rules2" >
        <div v-if="cancelForm.action == 'cancel'">是否取消此销售询价？</div>
        <el-form-item label="未成交原因：" prop="unOrderReason" v-if="cancelForm.action == 'unOrder'">
              <el-select v-model="cancelForm.unOrderReason">
                  <el-option :value="item.reasonValue" :label="item.reasonValue" v-for="item in reasonList" :key="item.reasonId"></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="备注：" v-show="cancelForm.action == 'unOrder'">
          <el-input v-model="cancelForm.unOrderRemark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>
<script>
    import axios from 'axios'
    import {getCustomerOption,getAddressList,getOrderUsersList,getCustomerSetting,orderGoodsList,getGoodsInquiryList} from '@/api/partner'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    import {addGoodsInquiry, changeInquiryInfo,getCrmGoodsList,inquiryUnOrderReasonList} from "../../api/partner";
    let time = new Date();
    let startDate = formatDate(time, 'yyyy-MM-dd');
    const defaultListQuery={
      "inquiryDate" : [startDate,startDate], //#询价时间
      "inquiryState" : 0,  //询价状态(0:待报价,5询价中，10已取消，15已过期,20已报价，30未成交，40已成交)
      "goodsName" : "",//商品品类
      "goodsSn" : "", //商品牌号
      "userId" : null, //询价人
      tab:'my',
      "pageNum"  : 1,
      "pageSize" : 10
    };

    const defaultAddForm={
      "customerId": '',   //客户ID
      customerName:'',
      customerLabel:'',
      customerIndustry:'',
      "goodsList" : [
        {
          "goodsName" : "",  //品类
          "goodsSn" : "", //商品牌号
          "kingGoodsId" : '', //商品SAPID
          "inquiryNum" : '',  //询价数量
          "receiveArea" : "", //送货地
          "receiveAreaList":[],
          "expectDeliverDays" : '', //交期天数，0表示现货
          list:[],
        }
      ],
      "inquiryRemark" : ""  //备注

    };

    const defaultGoodsItem={
      "goodsName" : "",  //品类
      "goodsSn" : "", //商品牌号
      "kingGoodsId" : '', //商品SAPID
      "inquiryNum" : '',  //询价数量
      "receiveArea" : "", //送货地
      "expectDeliverDays" : '', //交期天数，0表示现货
      receiveAreaList:[],
      list:[],
    };

    const defaultCancelForm={
      "inquiryId" : '', //询价ID
      "action" : "", //操作类型(未成交：unOrder, 取消:cancel)
      "unOrderReason" : "",  //未成交原因
      "unOrderRemark" : ""   //未成交备注
    };

    export default {
      name: "index",
      data(){
          return {
            roles:store.getters.roles ? store.getters.roles : [],
            listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
            tableData1: [],
            count1: 0,
            listLoading1: false,
            goodsList:[],
            userOptionList:[],

            addForm:JSON.parse(JSON.stringify(defaultAddForm)),
            dialogVisible:false,
            btnLoading:false,
            customerIndustryList:[],
            options:[],
            goodsLoading:false,
            rules:{
              customerName:[{required: true, message: '此项必填', trigger: 'change'},],
              customerLabel:[{required: true, message: '此项必填', trigger: 'change'},],
              customerIndustry:[{required: true, message: '此项必填', trigger: 'change'},],
              kingGoodsId:[{required: true, message: '此项必填', trigger: 'change'},],
              inquiryNum:[{required: true, message: '此项必填', trigger: 'blur'},],
              expectDeliverDays:[{required: true, message: '此项必填', trigger: 'blur'},],
              receiveAreaList:[{required: true, message: '此项必填', trigger: 'change'},],
            },


            dialogVisible2:false,
            cancelForm:JSON.parse(JSON.stringify(defaultCancelForm)),
            btnLoading2:false,
            rules2:{
              unOrderReason:[{required: true, message: '此项必填', trigger: 'change'},],
            },

            reasonList:[]

          }
      },
      computed: {
        ...mapGetters([
          'name',
          'mobile',
          'userId'
        ]),
        inquiryExport(){
          if(this.roles.indexOf("inquiryExport") != -1){
            return true
          }else{
            return false
          }
        },
      },
      created() {
        this.getUserOptionList();
        this.getCustomerSettingList();
        this.getAddressListData();
        orderGoodsList().then((res)=>{
          this.goodsList = res.list
        })
        inquiryUnOrderReasonList().then((res)=>{
          this.reasonList = res
        })
        this.getList1();


      },
      filters: {
        fifitem(item){
          return item.goodsName+'/'+item.goodsSn
        },
        fifInquiryState(val){
          if(val == 0){
            return '待报价'
          }else if(val == 5){
            return '询价中'
          }else if(val == 10){
            return '已取消'
          }else if(val == 15){
            return '已过期'
          }else if(val == 20){
            return '已报价'
          }else if(val == 30){
            return '未成交'
          }else if(val == 40){
            return '已成交'
          }
        },
      },
      methods:{
        changeInquiryState(val){
          this.handleSearchList1();
        },
        //获取销售询价列表
        getList1(){
          this.listLoading1 = true;
          let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
          getGoodsInquiryList(listQuery).then(response => {
            this.tableData1 = response.list;
            this.count1 = response.count;
            this.listLoading1 = false;
          }).catch(()=>{
            this.listLoading1 = false;
          });
        },

        handleSizeChange1(val){
          this.listQuery1.pageNum = 1;
          this.listQuery1.pageSize = val;
          this.getList1();
        },
        handleCurrentChange1(val){
          this.listQuery1.pageNum = val;
          this.getList1();
        },

        handleSearchList1(){
          this.listQuery1.pageNum = 1;
          this.getList1();
        },

        //下载excle
        downloadExcel(){
          let params = JSON.parse(JSON.stringify(this.listQuery1));
          params.isExport = 1;
          getGoodsInquiryList(params).then((res)=>{
            require.ensure([], () => {
              const { export_json_to_excel } = require('sheet/Export2Excel');
              const tHeader = res.title;
              const filterVal = res.columns;
              const list = res.list;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, res.fileName);
            })
          })
        },

        //下载表格数据格式化
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => v[j]))
        },

        //获取省市区列表
        getAddressListData(){
          getAddressList().then((res)=>{
            this.options = res;
          })
        },

        //地区切换
        changeArea(index,receiveAreaList){
          let data = {};
          data.kingGoodsId = this.addForm.goodsList[index].kingGoodsId;
          data.goodsName = this.addForm.goodsList[index].goodsName;
          data.goodsSn = this.addForm.goodsList[index].goodsSn;
          data.inquiryNum = this.addForm.goodsList[index].inquiryNum;
          data.receiveArea = receiveAreaList.join("");
          data.receiveAreaList = receiveAreaList;
          data.expectDeliverDays = this.addForm.goodsList[index].expectDeliverDays;
          data.list = this.addForm.goodsList[index].list;
          this.addForm.goodsList.splice(index,1,data);
        },

        //联想商品
        remoteMethod(key,index){
          this.goodsLoading = true;
          getCrmGoodsList({keyword:key}).then((res)=>{
            this.addForm.goodsList[index].list = res;
            this.goodsLoading = false;
          }).catch(()=>{
            this.goodsLoading = false;
          })
        },

        //切换商品
        changeGoods(index,kingGoodsId){
          let c = {};
          c = this.addForm.goodsList[index].list.find((el)=>{
            return el.kingGoodsId == kingGoodsId;
          });
          let data = {};
          data.kingGoodsId = c.kingGoodsId;
          data.goodsName = c.goodsName;
          data.goodsSn = c.goodsSn;
          data.inquiryNum = this.addForm.goodsList[index].inquiryNum;
          data.receiveArea = this.addForm.goodsList[index].receiveArea;
          data.receiveAreaList = this.addForm.goodsList[index].receiveAreaList;
          data.expectDeliverDays = this.addForm.goodsList[index].expectDeliverDays;
          data.list = this.addForm.goodsList[index].list;
          this.addForm.goodsList.splice(index,1,data);
          console.log("data",data);
          console.log("this.addForm",this.addForm)
        },

        //获取客户配置
        getCustomerSettingList(){
          getCustomerSetting().then((res)=>{
            res.forEach((el)=>{
             if(el.cdtCode == 'customer_industry'){
                this.customerIndustryList = el.data;
              }
            });
          })
        },

        //新增询价商品
        addGoods(){
          let item = JSON.parse(JSON.stringify(defaultGoodsItem))
          this.addForm.goodsList.push(item)
          console.log("this.addForm",this.addForm)
        },

        //删除询价商品
        delGoods(index){
          this.addForm.goodsList.splice(index,1);
        },

        //显示取消或未成交原因弹窗
        showCancelForm(item,action){
          this.dialogVisible2 = true;
          this.cancelForm = JSON.parse(JSON.stringify(defaultCancelForm));
          this.cancelForm.inquiryId = item.inquiryId;
          this.cancelForm.action = action;
        },

        //关闭取消或未成交原因弹窗
        handleClose2(){
          this.dialogVisible2 = false;
          this.btnLoading2 = false;
        },

        //提交取消或未成交原因
        handleConfirm2(){
          this.$refs.cancelForm.validate((valid) => {
            if (valid) {
              this.btnLoading2 = true;
              changeInquiryInfo(this.cancelForm).then((res)=>{
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.btnLoading2 = false;
                this.handleClose2();
                this.getList1();
              }).catch(()=>{
                this.btnLoading2 = false;
              })
            }
          })

        },



        //显示新增询价弹窗
        showAddForm(item){
          this.dialogVisible = true;
          this.addForm = JSON.parse(JSON.stringify(defaultAddForm));
        },
        //关闭新增询价弹窗
        handleClose(){
          this.dialogVisible = false;
          this.btnLoading = false;
        },

        //确认新增询价
        handleConfirm(){
          this.$refs.addForm.validate((valid) => {
            if (valid) {
              this.btnLoading = true;
              let data = {};
              data.customerId = this.addForm.customerId;
              data.customerLabel = this.addForm.customerLabel;
              data.customerIndustry = this.addForm.customerIndustry;
              data.inquiryRemark = this.addForm.inquiryRemark;
              data.goodsList = [];
              this.addForm.goodsList.forEach((el)=>{
                 data.goodsList.push({
                   goodsName:el.goodsName,
                   goodsSn:el.goodsSn,
                   kingGoodsId:el.kingGoodsId,
                   inquiryNum:el.inquiryNum,
                   receiveArea:el.receiveArea,
                   expectDeliverDays:el.expectDeliverDays
                 })
              })
              addGoodsInquiry(data).then((res)=>{
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.btnLoading = false;
                this.handleClose();
                this.getList1();
              }).catch(()=>{
                this.btnLoading = false;
              })
            }
          })

        },

          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList().then((res)=>{
                  this.userOptionList = res;
              })
          },

          //选择员工名称
          handleSelectUserName(key,item){
              this.listQuery1[key] = item.userId;
          },


          //客户名称输入匹配
          querySearch(queryString, cb){
              getCustomerOption({keywords:queryString}).then((res)=>{
                  cb(res);
              })
          },


          //选择客户名称
          handleSelectCustomerName(item){
              this.addForm.customerId = item.customerId;
              this.addForm.customerName = item.customerName
          },

        /**
         * 切换选择状态
         */
        handleSelect(key, keyPath){
          this.listQuery1 = JSON.parse(JSON.stringify(defaultListQuery));
          this.listQuery1.tab = key;
          this.handleSearchList1();
        },



      },
    }
</script>

<style scoped lang="scss">
  .upload-div{
    text-align: center;
    position:relative;
    #upload{

      opacity: 0;
      position: absolute;
      z-index: 1;
      width:154px;
      height:40px
    }
  }
  .title-tab{
    border-radius: 8px;
    background: #eee;
    margin-left: 10px;
    display: inline-block;
    vertical-align: middle;
    line-height: 20px;
    padding: 0 5px;
    color: #666;
  }
</style>
